package pandabay2.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import pandabay2.DAO.UserDAO;
import pandabay2.domain.User;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String message = "";
		try {
			System.out.println("In the Login Servlet");
			User user = new User();
			user.setEmail(request.getParameter("email"));
			user.setPassword(request.getParameter("password"));
			user = UserDAO.login(user);
			if(user.isValid()) {
				HttpSession session = request.getSession(true);
				// see it the session is actually a new session (e.g. if someone switches users on the same browser)
				if (session.isNew() == false) {
					session.invalidate();
					session = request.getSession(true);
					} 
				session.setAttribute("currentSessionUser",user);
				session.setAttribute("user_id", user.getUser_id());
				request.setAttribute("firstName", user.getFirstName());
				request.getRequestDispatcher("/LoginSuccess.jsp").forward(request, response);
			} else
				message = "Die Anmeldung ist leider fehlgeschlagen. Bitte korrekte Zugangsdaten eingeben.";
				request.setAttribute("message", message);
				request.getRequestDispatcher("/LoginFailed.jsp").forward(request, response);
		} catch (Throwable exc)
		{
			System.out.println(exc);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
}